package com.gdust.lease.web.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gdust.lease.common.exception.LeaseException;
import com.gdust.lease.common.result.ResultCodeEnum;
import com.gdust.lease.model.entity.*;
import com.gdust.lease.model.enums.ItemType;
import com.gdust.lease.web.admin.mapper.*;
import com.gdust.lease.web.admin.service.*;
import com.gdust.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.gdust.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.gdust.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.gdust.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.gdust.lease.web.admin.vo.fee.FeeValueVo;
import com.gdust.lease.web.admin.vo.graph.GraphVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author syun
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2025-1-1 15:02:07
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {
    //注入图片信息表的service
    @Autowired
    private GraphInfoService graphInfoService;

    //注入公寓&配套关联表的service
    @Autowired
    private ApartmentFacilityService apartmentFacilityService;

    //注入公寓&杂费关联表的service
    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;

    //注入公寓标签关联表的service
    @Autowired
    private ApartmentLabelService apartmentLabelService;

    //注入公寓信息表的mapper
    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;

    //注入图片信息表的mapper
    @Autowired
    private GraphInfoMapper graphInfoMapper;

    //注入标签信息表的mapper
    @Autowired
    private LabelInfoMapper labelInfoMapper;

    //注入配套信息表的mapper
    @Autowired
    private FacilityInfoMapper facilityInfoMapper;

    //注入杂项费用值表的mapper
    @Autowired
    private FeeValueMapper feeValueMapper;

    //注入房间信息表的mapper
    @Autowired
    private RoomInfoMapper roomInfoMapper;


    /**
     * 保存或更新公寓信息
     * <p>
     * 注：还有公寓信息,需要先查询公寓信息
     * 思路：由于保存或更新公寓信息涉及条件较多，此处直接先删除再修改
     *
     * @param apartmentSubmitVo 公寓信息VO,内含：公寓配套id、公寓标签id、公寓杂费值id、公寓图片id
     */
    @Override
    public void saveOrUpdateApartment(ApartmentSubmitVo apartmentSubmitVo) {
        //判断公寓信息是否为空
        boolean isUpdate = apartmentSubmitVo.getId() != null;
        //更新ApartmentInfo表，因为apartmentSubmitVo继承自ApartmentInfo，因此super调用可以更新ApartmentInfo表
        super.saveOrUpdate(apartmentSubmitVo);

        //若公寓信息不为空则执行操作
        if (isUpdate) {
            //1.删除图片列表
            //注：删除图片，需要获取到它的图片ID和图片类型才可以删除
            LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            //判断图片类型是否为公寓
            graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
            //根据图片所有对象id匹配记录
            graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId, apartmentSubmitVo.getId());
            graphInfoService.remove(graphInfoLambdaQueryWrapper);

            //2.删除配套列表
            LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            //根据公寓 ID 匹配记录
            apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId, apartmentSubmitVo.getId());
            apartmentFacilityService.remove(apartmentFacilityLambdaQueryWrapper);

            //3.删除标签列表
            LambdaQueryWrapper<ApartmentLabel> apartmentLabelLambdaQueryWrapper = new LambdaQueryWrapper<>();
            //根据标签id匹配记录
            apartmentLabelLambdaQueryWrapper.eq(ApartmentLabel::getLabelId, apartmentSubmitVo.getLabelIds());
            apartmentLabelService.remove(apartmentLabelLambdaQueryWrapper);

            //4.删除杂费列表
            LambdaQueryWrapper<ApartmentFeeValue> apartmentFeeValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
            //根据收费项value_id匹配记录
            apartmentFeeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getFeeValueId, apartmentSubmitVo.getFeeValueIds());
            apartmentFeeValueService.remove(apartmentFeeValueLambdaQueryWrapper);
        }

        //1.插入图片列表
        List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();//获取公寓图片id列表
        //如果公寓图片id列表不为空，进行后续处理
        if (!CollectionUtils.isEmpty(graphVoList)) {
            //新建图片信息表集合，用于存储图片信息表对象
            ArrayList<GraphInfo> graphInfoList = new ArrayList<>();
            // 遍历 graphVoList，逐一处理每个 GraphVo 对象
            for (GraphVo graphVo : graphVoList) {
                //新建GraphInfo图片信息表对象，用于设置属性值
                GraphInfo graphInfo = new GraphInfo();
                graphInfo.setItemType(ItemType.APARTMENT);//设置图片所属对象类型为公寓
                graphInfo.setItemId(apartmentSubmitVo.getId());//设置公寓id(从公寓信息VO类中获取)
                graphInfo.setName(graphVo.getName());//设置公寓名称(从图片信息类中获取)
                graphInfo.setUrl(graphVo.getUrl());//设置图片地址(从图片信息类中获取)
                graphInfoList.add(graphInfo);//将图片信息表对象放入集合中
            }
            //批量保存图片信息表集合到数据库
            graphInfoService.saveBatch(graphInfoList);
        }

        //2.插入配套列表
        List<Long> facilityInfoIdList = apartmentSubmitVo.getFacilityInfoIds();//获取公寓配套id列表
        //如果公寓配套id列表不为空，进行后续操作
        if (!CollectionUtils.isEmpty(facilityInfoIdList)) {
            //新建公寓设备表集合，用于存储公寓信息表对象
            ArrayList<ApartmentFacility> facilityArrayList = new ArrayList<>();
            // 遍历 facilityInfoIdList集合，逐一处理每个 facilityId 对象
            for (Long facilityId : facilityInfoIdList) {
                //新建公寓设备表对象，用于设置属性值
                ApartmentFacility apartmentFacility = new ApartmentFacility();
                apartmentFacility.setApartmentId(apartmentSubmitVo.getId());//设置公寓id(从公寓信息VO类中获取)
                apartmentFacility.setFacilityId(facilityId);//设置设施id(表示当前遍历到的元素)
                facilityArrayList.add(apartmentFacility);//将公寓设备表对象放入集合中
            }
            //批量保存公寓设备表集合到数据库中
            apartmentFacilityService.saveBatch(facilityArrayList);
        }


        //3.插入标签列表
        List<Long> labelIdList = apartmentSubmitVo.getLabelIds();//获取公寓标签id列表
        //如果公寓标签id列表不为空
        if (!CollectionUtils.isEmpty(labelIdList)) {
            //新建公寓标签表集合，用于存储公寓标签表对象
            ArrayList<ApartmentLabel> apartmentLabelArrayList = new ArrayList<>();
            //遍历labelIdList集合，逐一处理labelId对象
            for (Long labelId : labelIdList) {
                //新建公寓标签表对象，用于设置属性
                ApartmentLabel apartmentLabel = new ApartmentLabel();
                apartmentLabel.setApartmentId(apartmentSubmitVo.getId());
                apartmentLabel.setLabelId(labelId);//设置标签id(表示当前遍历到的元素)
                apartmentLabelArrayList.add(apartmentLabel);//将公寓标签表对象放入集合中
            }
            //批量保存公寓标签表集合到数据库中
            apartmentLabelService.saveBatch(apartmentLabelArrayList);
        }


        //4.插入杂费列表
        List<Long> feeValueIdList = apartmentSubmitVo.getFeeValueIds();//获取公寓杂费值id列表
        //如果公寓杂费值id列表不为空，执行下面操作
        if (!CollectionUtils.isEmpty(feeValueIdList)) {
            //新建公寓杂费表集合，用于存储公寓杂费表对象
            ArrayList<ApartmentFeeValue> apartmentFeeValueArrayList = new ArrayList<>();
            //遍历feeValueIdList集合，逐一处理feeValueId
            for (Long feeValueId : feeValueIdList) {
                //新建公寓杂费表对象，用于设置属性
                ApartmentFeeValue apartmentFeeValue = new ApartmentFeeValue();
                apartmentFeeValue.setApartmentId(apartmentSubmitVo.getId());//设置公寓id(从公寓信息VO类中获取)
                apartmentFeeValue.setFeeValueId(feeValueId);//设置收费项value_id(表示当前遍历到的元素)
                apartmentFeeValueArrayList.add(apartmentFeeValue);//将公寓杂费表对象放入集合中
            }
            //批量保存公寓杂费表集合到数据库中
            apartmentFeeValueService.saveBatch(apartmentFeeValueArrayList);
        }

    }

    /**
     * 根据查询条件获取分页后的公寓列表
     *
     * @param page    当前页
     * @param queryVo 查询条件
     * @return
     */
    @Override
    public IPage<ApartmentItemVo> pageApartmentItemByQuery(IPage<ApartmentItemVo> page, ApartmentQueryVo queryVo) {
        //自定义查询：根据查询条件获取分页后的公寓列表
        return apartmentInfoMapper.pageApartmentItemByQuery(page, queryVo);
    }

    /**
     * 根据ID获取公寓详细信息
     * <p>
     * 注：还有公寓信息,需要先查询公寓信息
     * 公寓信息VO包含：图片列表、标签列表、配套列表、杂费列表
     *
     * @param id 传入的公寓id
     * @return
     */
    @Override
    public ApartmentDetailVo getApartmentDetailById(Long id) {
        //1.查询ApartmentInfo
        ApartmentInfo apartmentInfo = this.getById(id);
        if (apartmentInfo == null) {
            return null;
        }

        //2.查询GraphInfo
        //自定义查询：查询图片信息表，过滤条件：图片所属对象类型为公寓，图片所属对象id为公寓id
        List<GraphVo> graphVoList = graphInfoMapper.selectListByItemTypeAndId(ItemType.APARTMENT, id);

        //3.查询LabelInfo
        //自定义查询：根据传入的公寓id查询标签信息表
        List<LabelInfo> labelInfoList = labelInfoMapper.selectListByApartmentId(id);

        //4.查询FacilityInfo
        //自定义查询：根据传入的公寓id查询设备信息表
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.selectListByApartmentId(id);


        //5.查询FeeValue
        //自定义查询：根据传入的公寓id查询杂费信息表
        List<FeeValueVo> feeValueVoList = feeValueMapper.selectListByApartmentId(id);

        //6.组装结果
        ApartmentDetailVo apartmentDetailVo = new ApartmentDetailVo();
        //将对象的属性值(源对象)拷贝到目标对象的对应属性，前提是属性名和类型一致
        BeanUtils.copyProperties(apartmentInfo, apartmentDetailVo);
        //此处为apartmentDetailVo特有的属性，需要单独设置
        apartmentDetailVo.setGraphVoList(graphVoList);
        apartmentDetailVo.setLabelInfoList(labelInfoList);
        apartmentDetailVo.setFacilityInfoList(facilityInfoList);
        apartmentDetailVo.setFeeValueVoList(feeValueVoList);

        return apartmentDetailVo;
    }

    /**
     * 根据id删除公寓信息
     * <p>
     * 思路：首先需要删除公寓信息，再删除与公寓信息表关联的内容:图片信息表、公寓标签信息表、公寓设备信息表、公寓杂费信息表
     * <p>
     * 注：由于公寓下会包含房间信息，因此在删除公寓时最好先判断一下该公寓下是否存在房间信息，
     * 若存在，则提醒用户先删除房间信息后再删除公寓信息。
     *
     * @param id 传入的公寓id
     */
    @Transactional
    @Override
    public void removeApartmentById(Long id) {

        //因为公寓下面有房间，先检查公寓下是否存在房间，如果没有则直接删除，如果有就终止删除并且提醒用户公寓下有房间，删除公寓需先删除房间信息删除
        LambdaQueryWrapper<RoomInfo> roomInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //匹配传入的公寓id是否为所属公寓id
        roomInfoLambdaQueryWrapper.eq(RoomInfo::getApartmentId, id);
        Long count = roomInfoMapper.selectCount(roomInfoLambdaQueryWrapper);

        //如果count≤0没有房间,则正常运行下面删除逻辑
        if (count > 0) {
            //抛出自定义异常：请先删除房间
            //直接为前端返回如下响应：先删除房间信息再删除公寓信息
            throw new LeaseException(ResultCodeEnum.ADMIN_APARTMENT_DELETE_ERROR);
        }

        //0.删除公寓信息表的内容
        super.removeById(id);

        //1.删除图片信息表
        LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //匹配图片信息表所属类型是否为公寓
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
        //匹配传入公寓id是否为图片所有对象id
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId, id);
        graphInfoService.remove(graphInfoLambdaQueryWrapper);

        //2.删除公寓标签表
        LambdaQueryWrapper<ApartmentLabel> apartmentLabelLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //匹配传入公寓id是否为公寓id
        apartmentLabelLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId, id);
        apartmentLabelService.remove(apartmentLabelLambdaQueryWrapper);


        //3.删除公寓设备表
        LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //匹配传入公寓id是否为公寓id
        apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId, id);
        apartmentFacilityService.remove(apartmentFacilityLambdaQueryWrapper);

        //4.删除公寓杂费表
        LambdaQueryWrapper<ApartmentFeeValue> apartmentFeeValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //匹配传入公寓id是否为公寓id
        apartmentFeeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId, id);
        apartmentFeeValueService.remove(apartmentFeeValueLambdaQueryWrapper);

    }

}




